package yz.cp.back.auth.oauth.exception;

import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer;
import org.springframework.security.oauth2.provider.error.OAuth2ExceptionRenderer;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomOauthAccessDeniedHandler implements AccessDeniedHandler {
    private WebResponseExceptionTranslator exceptionTranslator = new CustomWebResponseExceptionTranslator();
    private OAuth2ExceptionRenderer exceptionRenderer = new DefaultOAuth2ExceptionRenderer();
    private HandlerExceptionResolver handlerExceptionResolver = new DefaultHandlerExceptionResolver();
    public CustomOauthAccessDeniedHandler() {
    }

    public CustomOauthAccessDeniedHandler(WebResponseExceptionTranslator exceptionTranslator) {
        this.exceptionTranslator = exceptionTranslator;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        this.doHandle(request, response, authException);
    }

    void doHandle(HttpServletRequest request, HttpServletResponse response, Exception authException) throws IOException, ServletException {
        try {
            ResponseEntity<OAuth2Exception> result = this.exceptionTranslator.translate(authException);
            result = this.enhanceResponse(result, authException);
            this.exceptionRenderer.handleHttpEntityResponse(result, new ServletWebRequest(request, response));
            response.flushBuffer();
        } catch (ServletException var5) {
            if (this.handlerExceptionResolver.resolveException(request, response, this, var5) == null) {
                throw var5;
            }
        } catch (IOException var6) {
            throw var6;
        } catch (RuntimeException var7) {
            throw var7;
        } catch (Exception var8) {
            throw new RuntimeException(var8);
        }
    }

    public ResponseEntity<OAuth2Exception> enhanceResponse(ResponseEntity<OAuth2Exception> result, Exception authException) {
        return result;
    }
}
